# -*- encoding=UTF-8 -*-
import json
import os
import time
from datetime import datetime
from time import sleep

import requests
import uiautomator2 as u2


class luke:

    def __init__(self, devices_name, packageName):
        self.packageName = packageName
        # self.d = u2.connect_usb(devices_name)
        self.d = u2.connect(devices_name)
        self.d.unlock()
        self.d.press("home")
        self.dingTalk = DingMessage()
        self.log_path = time.strftime("lock_%Y_%m_%d_%H_%M_%S", time.localtime()) + '.log'

    def set_up(self):
        self.d.app_stop(self.packageName)
        sleep(1)
        self.d.app_start(self.packageName)


    def test_down(self):
        self.d.app_stop(self.packageName)

    def write_log(self, file_path, str):
        '''
        报告录入工具
        :param str: 字符串
        :return: None
        '''
        if file_path is not None:
            t = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
            with open(file_path, "a") as file:
                file.write(t + " " + str + "\n")
                file.close()

    def start_lock(self, test_num):
        try:
            is_output = False
            if self.d(text="test lock").exists():
                # 在首页则需要进入插件
                self.d(text="test lock").click(timeout=5)

            time.sleep(2)
            start_monitor_time = time.time()
            while int(time.time()) - int(start_monitor_time) < 10:
                # 等待10秒出图
                if self.d(resourceId="com.wyze.gwell:id/iv_call").info['enabled']:
                    is_output = True
                    break
                time.sleep(1)

            if is_output:
                # 如果已经出图
                start_time = time.time()
                self.d(resourceId="com.wyze.gwell:id/mars_img_lock").click(timeout=5)
                while int(time.time()) - int(start_time) < 30:
                    toast_msg = self.d.toast.get_message(wait_timeout=1, cache_timeout=1, default=None)

                    if toast_msg is None:
                        continue

                    elif "Unlocked successfully" in toast_msg:
                        end_time = time.time()
                        total_time = end_time - start_time
                        self.write_log(self.log_path, str="第" + str(test_num) + "次测试，开锁成功，耗时#" + str(total_time))
                        self.dingTalk.test_pass(take_time=str(total_time), test_num=test_num)
                        return True
                    elif "Operation failed" in toast_msg:
                        self.write_log(self.log_path, str="第" + str(test_num) + "次测试，开锁失败")
                        self.dingTalk.test_fail(test_num=test_num, info="Operation failed")
                        return False

                self.write_log(self.log_path, str="第" + str(test_num) + "次测试，开锁失败")
                self.dingTalk.test_fail(test_num=test_num, info="捕捉不到toast")
                return True
            else:
                self.write_log(self.log_path, str="第" + str(test_num) + "次测试，出图失败")
                self.dingTalk.test_fail(test_num=test_num, info="出图失败")
                self.set_up()
                return False

        except Exception as e:
            print(e)
            self.set_up()
            return False


class DingMessage:
    def __init__(self):
        self.URL = "https://oapi.dingtalk.com/robot/send?" \
                   "access_token=5d64a341f0db2ca64a905d9ace93b39b1746fea85926ec2691273c80eb5305dd"  # Webhook地址

        self.headers = {'Content-Type': 'application/json'}

    def test_fail(self, test_num, info):
        data_dict = {
            "msgtype": "markdown",
            "markdown": {
                "title": "开锁压力测试异常提示",
                "text": "#### **<font color=#FF0000>第" + str(test_num) + "次测试异常，开锁失败，错误信息：" + info +
                                                                         "**</font>\n\n"
            }
        }
        json_data = json.dumps(data_dict)
        requests.post(self.URL, data=json_data, headers=self.headers, timeout=3)


    def test_pass(self, test_num, take_time):
        data_dict = {
            "msgtype": "markdown",
            "markdown": {
                "title": "开锁压力测试通过提示",
                "text": "#### **<font color=#7CFCOO>第" + str(test_num)
                        + "次测试通过**</font>\n\n""> **开锁消耗时长:** <font color=#000000>"
                        + str(take_time) + "秒</font>\n\n"
            }
        }
        json_data = json.dumps(data_dict)
        requests.post(self.URL, data=json_data, headers=self.headers, timeout=3)


if __name__ == '__main__':
    test_time = int(input("请输入测试次数："))
    lk = luke(devices_name="0.0.0.0", packageName='com.wyze.gwell')
    # lk = luke(devices_name="R5CR11R7GBZ", packageName='com.wyze.gwell')

    count = 1
    lk.set_up()
    while count < test_time + 1:
        time.sleep(8)
        lk.start_lock(test_num=count)
        count = count + 1
